package com.hx.netty.chat.protocol;

import com.sun.deploy.util.StringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.internal.StringUtil;
import org.msgpack.MessagePack;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Huathy
 * @date 2021-10-24 22:17
 * @description
 */
public class ImDecoder extends ByteToMessageDecoder {
    // 表示 [消息头] -
    private Pattern pattern = Pattern.compile("^\\[(.*)(\\s\\-\\s(.*))?\\]");

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        final int length = in.readableBytes();
        final byte[] array = new byte[length];

        // 将网络传输过来的内容变为一个字符串
        String content = new String(array, in.readerIndex(), length);

        // 判空，空消息不做解析
        if (StringUtil.isNullOrEmpty(content)) {
            ctx.channel().pipeline().remove(this);
            return;
        }

        //将字符串变为一个能够识别的ImMsg对象
        in.getBytes(in.readerIndex(), array, 0, length);
        //利用序列化框架，将网络流信息，直接转化为imMsg对象
        out.add(new MessagePack().read(array, ImMsg.class));
        in.clear();
    }

    public ImMsg decode(String msg)  {
        if (StringUtil.isNullOrEmpty(msg)) {
            return null;
        }
        Matcher matcher = pattern.matcher(msg);
        String header = "";
        String content = "";
        if (matcher.matches()) {
            header = matcher.group(1);
            content = matcher.group(3);
        }
        String[] headers = header.split("\\]\\[");
        long time = Long.parseLong(headers[1]);
        String nickName = headers[2].length() < 10 ? headers[2] : headers[2].substring(0, 9);
        if (msg.startsWith("[" + IMP.LOGIN.getName() + "]")) {
            return new ImMsg(headers[0], headers[3], time, nickName);
        } else if (msg.startsWith("[" + IMP.CHAT.getName() + "]")) {
            return new ImMsg(headers[0], time, nickName, content);
        } else if (msg.startsWith("[" + IMP.FLOWER.getName() + "]")) {
            return new ImMsg(headers[0], headers[3], time, nickName);
        } else {
            return null;
        }
    }
}
